<?php

namespace app\Home\controller;

use think\Controller;
use app\common\controller\Home;

class team extends Home
{   
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->CommissionModel = model('Business.Commission');
        $this->SubjectModel = model('Subject.Subject');
        $this->RecordModel = model('Business.Record');
    } 

    //我的团队
    public function index()
    {
        $list = $this->BusinessModel->where(['parentid' => $this->view->AutoLogin['id']])->select();
         
        $this->assign('list',$list);

        return $this->view->fetch();
    }

    //海报界面
    public function poster()
    {    
        
        //获取当前封面海报和头像
        $poster = isset($this->view->AutoLogin['poster']) ? 
        trim($this->view->AutoLogin['poster']) : '';
        $avatar = isset($this->view->AutoLogin['avatar']) ?
        trim($this->view->AutoLogin['avatar']) : '';
        $id = isset($this->view->AutoLogin['id']) ?
        trim($this->view->AutoLogin['id']) : 0;
        $mobile = isset($this->view->AutoLogin['mobile']) ? 
        trim($this->view->AutoLogin['mobile']) : '';

        // 推广链接 http://www.fast.com/home/index/register?busid=
        //设置一个签证 用于验证身份信息 将id和mobile进行md5加密
        //$token签证，$domain域名
        $domain = $this->request->domain();
        $token = md5($id.$mobile);
        $url = "$domain/index.php/home/index/register?token=$token";

        if($this->request->isAjax())
        {   
             //生成海报
             $qrcode = new \dh2y\qrcode\QRcode();
            

            $level = ['L','M','Q','H'];
            $index = array_rand($level);
             //生成二维码图片
             $path =  $qrcode -> png($url,false,5,$level[$index])    //将url地址写入
                     -> logo($avatar) //添加logo图片
                     -> getPath();
             
             //更新数据到数据库中
             $data = [
                 'id' => $this ->view -> AutoLogin['id'],
                 'poster' => $path
             ];

             //更新
             $result = $this->BusinessModel->isUpdate(true)->save($data);

             if($result === FALSE)
             {
                 //说明更新失败
                 $this->error('更新海报失败');
                 exit;
             }else
             {
                //判断海报是否存在,如果不存在就生成一张海报
                //文件为空或者文件不存在，有一个条件满足就为失败
                //若海报已存在，就要删除就旧海报
                is_file(".".$poster) && @unlink(".".$poster);
                
                 //返回数据
                 $this -> success('更新个人海报成功',null,['poster' => $path]); 
                 exit;
             }
         }
         
        //赋值数据
        $this ->assign('url',$url);

        return $this->view->fetch();
    }

     //提现记录
     public function commission()
     {
         if($this->request->isAjax())
         {
             $page = $this->request->param('page', 1, 'trim');
             $limit = $this->request->param('limit', 10, 'trim');
             $status = $this->request->param('status', 'all', 'trim');
             $start = ($page-1)*$limit;
 
             $where = ['commission.parentid' => $this->view->AutoLogin['id'], 'type' => 'subject'];
 
             if($status != "all")
             {
                 $where['commission.status'] = $status;
             }
 
             //查询数据总条数
             $count = $this->CommissionModel->with(['subject', 'business'])->where($where)->count();
 
             //查询数据
             $list = $this->CommissionModel
                 ->with(['subject', 'business'])
                 ->where($where)
                 ->limit($start, $limit)
                 ->order('commission.createtime', 'desc')
                 ->select();
 
             if($list)
             {
                 foreach($list as $item)
                 {
                     $subid = isset($item['subject']['subid']) ? trim($item['subject']['subid']) : 0;
 
                     $subject = $this->SubjectModel->where(['id' => $subid])->find();
 
                     $item['SubjectInfo'] = $subject ? $subject : [];
                 }
             }
 
             $data = [
                 'count' => $count,
                 'list' => $list
             ];
 
             if($list)
             {
                 //成功返回
                 $this->success('返回列表', null, $data);
                 exit;
             }else
             {
                 //失败返回
                 $this->error('暂无数据', null, $data);
                 exit;
             }
         }
 
         return $this->view->fetch();
     }
     
      //提现
    public function recover()
    {
        if($this->request->isAjax())
        {
            $comid = $this->request->param('comid', 'trim', 0);

            //查询提现的信息
            $where = ['parentid' => $this->view->AutoLogin['id'], 'id' => $comid];
            
            $commission = $this->CommissionModel->where($where)->find();

            if(!$commission)
            {
                $this->error('提现记录不存在');
                exit;
            }

            if($commission['status'] == '1')
            {
                $this->error('该记录已提现不能重复提现');
                exit;
            }

            //客户表更新余额、消费记录表添加提现记录，更新佣金表提现状态
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CommissionModel->startTrans();

            $amount = $commission['amount'] > 0 ? $commission['amount'] : 0;
            $money = $this->view->AutoLogin['money'];

            if($amount <= 0)
            {
                $this->error('提现余额不能小于0元');
                exit;
            }

            //提现余额相加
            $UpdateMoney = bcadd($amount, $money);

            $BusinessData = [
                'id' => $this->view->AutoLogin['id'],
                'money' => $UpdateMoney
            ];

            $validate = [
                [
                  'money' => ['number', 'egt:0'],
                ],
                [
                  'money.number'  => '余额必须是数字类型',
                  'money.egt'      => '余额不足请先充值',
                ]
            ];

            $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //business_record 消费记录表
            $content = "提现佣金，￥ $amount 元";
            $RecordData = [
                'total' => "$amount",
                'content' => $content,
                'busid' => $this->view->AutoLogin['id']
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $this->BusinessModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            //business_commission 佣金状态修改
            $CommissionData = [
                'id' => $commission['id'],
                'status' => '1'
            ];

            $CommissionStatus = $this->CommissionModel->isUpdate(true)->save($CommissionData);

            if($CommissionStatus === FALSE)
            {
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->error($this->CommissionModel->getError());
                exit;
            }

            if($BusinessStatus === FALSE || $RecordStatus === FALSE || $CommissionStatus === FALSE)
            {
                $this->CommissionModel->rollback();
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->error("提现失败");
                exit;
            }else
            {
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->CommissionModel->commit();
                $this->success('提现成功');
                exit;
            }
        }
    }
}
